package com.xdog.web3.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.xdog.common.oss.factory.OssFactory;
import com.xdog.common.oss.core.OssClient;
import com.xdog.common.oss.entity.UploadResult;

import java.io.*;
import java.net.*;
import java.util.UUID;

/**
 * Twitter头像下载工具类
 */
@Slf4j
@Component
public class TwitterAvatarDownloader {

    // 代理配置
    @Value("${web3.api.proxy-host:127.0.0.1}")
    private String proxyHost = "127.0.0.1";

    @Value("${web3.api.proxy-port:7890}")
    private int proxyPort = 7890;

    /**
     * 下载Twitter用户头像并保存到OSS
     * @param avatarUrl 头像URL
     * @param userId 用户ID
     * @return OSS存储路径
     */
    public String downloadAvatar(String avatarUrl, String userId) {
        if (avatarUrl == null || avatarUrl.isEmpty()) {
            return null;
        }

        try {
            // 直接从URL获取输入流，配置代理
            URL url = new URL(avatarUrl);
            URLConnection connection = createURLConnectionWithProxy(url);
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
            
            try (InputStream in = connection.getInputStream()) {
                // 获取文件扩展名
                String fileExtension = getFileExtension(avatarUrl);
                
                // 上传到OSS
                OssClient ossClient = OssFactory.instance();
                // 使用默认前缀生成文件路径
                String objectName = ossClient.getPath("twitter/avatar", 
                    userId + "_" + UUID.randomUUID() + fileExtension);
                
                // 直接使用InputStream上传，避免创建临时文件
                UploadResult uploadResult = ossClient.upload(in, objectName, 
                    (long) connection.getContentLength(), connection.getContentType());

                log.info("成功上传Twitter用户头像到OSS: {}", uploadResult.getUrl());
                return uploadResult.getUrl();
            }
        } catch (Exception e) {
            log.error("上传Twitter用户头像到OSS失败: userId={}, url={}", userId, avatarUrl, e);
            return null;
        }
    }

    /**
     * 创建配置了代理的URLConnection
     * @param url 目标URL
     * @return 配置了代理的URLConnection
     * @throws IOException IO异常
     */
    private URLConnection createURLConnectionWithProxy(URL url) throws IOException {
        // 检查是否需要启用代理
        if (proxyHost != null && !proxyHost.isEmpty() && proxyPort > 0) {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
            return url.openConnection(proxy);
        } else {
            // 如果没有配置代理，则使用默认连接
            return url.openConnection();
        }
    }

    /**
     * 获取文件扩展名
     * @param url 文件URL
     * @return 扩展名
     */
    private String getFileExtension(String url) {
        try {
            String path = new URL(url).getPath();
            int lastDotIndex = path.lastIndexOf('.');
            if (lastDotIndex != -1) {
                return path.substring(lastDotIndex);
            }
        } catch (Exception e) {
            log.warn("解析文件扩展名失败: {}", url, e);
        }
        return ".jpg"; // 默认扩展名
    }
}